package com.sound.ampache;

/* Copyright (c) 2010 Brian Kirkman <kirkman.brian@gmail.com>
*
* +------------------------------------------------------------------------+
* | This program is free software; you can redistribute it and/or          |
* | modify it under the terms of the GNU General Public License            |
* | as published by the Free Software Foundation; either version 3         |
* | of the License, or (at your option) any later version.                 |
* |                                                                        |
* | This program is distributed in the hope that it will be useful,        |
* | but WITHOUT ANY WARRANTY; without even the implied warranty of         |
* | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          |
* | GNU General Public License for more details.                           |
* |                                                                        |
* | You should have received a copy of the GNU General Public License      |
* | along with this program; if not, write to the Free Software            |
* | Foundation, Inc., 59 Temple Place - Suite 330,                         |
* | Boston, MA  02111-1307, USA.                                           |
* +------------------------------------------------------------------------+
*
* Special thanks to the following: 
* Kevin Purdy, author of Amdroid, for much of the code used in this project
* 
* Jorge Ramon, author of MiamiCoder blog, for many great BlackBerry examples
* published on his blog.
* 
* 
*/

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;

class OptionsScreen extends MainScreen{
    
    private EditField serverUrlField;
    private EditField userField;
    private PasswordEditField passwordField;
    private ObjectChoiceField listConnection;
    private NumericChoiceField listFont;
    private CheckboxField checkCacheField;
    private CheckboxField checkUpdateField;
    private ButtonField btnClear;
    
    private String serverUrl;
    private String userName;
    private String password;
    private String fontSize;
    private String connType;
    private boolean checkCache;
    private boolean checkUpdate;
    
    private HelpScreen helpScreen;
    
    
    private MenuItem saveMenu = new MenuItem("Save",100,10) {
       public void run() {
           Screen screen = UiApplication.getUiApplication().getActiveScreen();
           try {
               screen.save();
           } catch (java.io.IOException ex) {
               Dialog.inform("Could not save settings.");
           }
           screen.close(); 
       } 
    };
    
    
    private MenuItem helpMenu = new MenuItem("Help",100,10) {
        public void run() {
            showHelpScreen();
        } 
     };
    
    OptionsScreen() {   
        this.setTitle("Options");        
                
        serverUrlField = new EditField("Server URL: ", "",256,EditField.FIELD_RIGHT);
        userField = new EditField("User:", "",256,EditField.EDITABLE);
        passwordField = new PasswordEditField("Password:", "",256,PasswordEditField.EDITABLE);
        checkCacheField = new CheckboxField("Cache Albums and Artists", true);
        checkUpdateField = new CheckboxField("Autoupdate Cache on Catalog Size Change", true);
        checkCacheField.setChangeListener(listenerCheckCache);
        btnClear = new ButtonField("Clear Cache");
        btnClear.setChangeListener(listenerBtnClear);
        listFont = new NumericChoiceField("Album, Artist, Song List Font Size:", 10, 30, 2);
        String choices[] = {"Auto", "WiFi", "Carrier", "BES-MDS", "Device"};
        listConnection = new ObjectChoiceField("Connection:", choices, 0);
        
        this.add(serverUrlField);
        this.add(userField);
        this.add(passwordField);
        this.add(listConnection);
        this.add(listFont);
        this.add(checkCacheField);
        this.add(checkUpdateField);
        this.add(btnClear);
    }
    
    
    protected void makeMenu(Menu menu, int instance) {
        menu.add(saveMenu);
        menu.add(helpMenu);
        menu.add(MenuItem.separator(helpMenu.getOrdinal() + 1));
        super.makeMenu(menu,instance);
    }
    
    
    public void displayOptions() {
        serverUrl = DataStore.getAppServerUrl();
        userName = DataStore.getUserName();
        password = DataStore.getPassword();
        fontSize = DataStore.getFontSize();
        connType = DataStore.getConnType();
        checkCache = DataStore.getCacheVal().booleanValue();
        checkUpdate = DataStore.getUpdateVal().booleanValue();
        
        serverUrlField.setText(serverUrl);
        userField.setText(userName);
        passwordField.setText(password);
        listFont.setSelectedValue(Integer.parseInt(fontSize));
        listConnection.setSelectedIndex(connType);
        checkCacheField.setChecked(checkCache);
        checkUpdateField.setChecked(checkUpdate);
        
        if (checkCache == true) {
        	checkUpdateField.setEditable(true);
        } else {
        	checkUpdateField.setEditable(false);
        }
        
        if((DataStore.getCachedAlbums().length == 0 || DataStore.getCachedAlbums() == null) &&
        		(DataStore.getCachedArtists().length == 0 || DataStore.getCachedArtists() == null)) {
        	btnClear.setEditable(false);
        } else {
        	btnClear.setEditable(true);
        }
        	
    }
    
    
    FieldChangeListener listenerCheckCache = new FieldChangeListener() {
    	public void fieldChanged(Field field, int context) {
    		if (checkCacheField.getChecked() == true) {
    			checkUpdateField.setEditable(true);
    		} else {
    			checkUpdateField.setEditable(false);
    		}
    	}
    };
    
    
    FieldChangeListener listenerBtnClear = new FieldChangeListener() {
    	public void fieldChanged(Field field, int context) {
    		clearCache();
    	}
    };
    
    
    public void clearCache() {
    	int ret = Dialog.ask(Dialog.D_YES_NO,
    		"Are you sure you want to clear cached albums and artists?",
    		Dialog.NO);
    	if (ret == Dialog.YES) {
    		DataStore.clearCachedAlbums();
    		DataStore.clearCachedArtists();
    		Dialog.alert("Cache Cleared");
    		serverUrlField.setFocus();
    		btnClear.setEditable(false);
    	}
    }
    
    
    public void save() throws java.io.IOException { 
    	boolean reAuth = false;
    	
    	//Only authenticate in the following scenarios.  Do this because
    	//a reauth will get a new auth token.
    	if (serverUrlField.getText().trim() != serverUrl ||
    			userField.getText().trim() != userName ||
    			passwordField.getText().trim() != password ||
    			listConnection.toString() != connType ||
    			ampacheberry.comm.authToken == "" ||
    			ampacheberry.comm.authToken == null) {
    		reAuth = true;
    	}
    	
        DataStore.setAppServerUrl(serverUrlField.getText().trim());
        DataStore.setUsername(userField.getText().trim());
        DataStore.setPassword(passwordField.getText().trim());
        DataStore.setConnType(listConnection.toString());
        DataStore.setFontSize(listFont.toString());
        DataStore.setCacheVal(new Boolean(checkCacheField.getChecked()));
        DataStore.setUpdateVal(new Boolean(checkUpdateField.getChecked()));
		
        ampacheberry.getStoreData();
		
		//reset Connection Type for player
		ampacheberry.setPlayerConnection();
        
		if (reAuth) {
			SplashScreen.showScreen(ampacheberry.authReq);
		}
    } 
    
    
    public void showHelpScreen() {
        if (null == helpScreen) {
            helpScreen = new HelpScreen();
        }
        UiApplication.getUiApplication().pushModalScreen(helpScreen);
    }
} 